package com.doform.android.xianggucheng.activity.downorder;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.doform.android.xianggucheng.BaseTimePickerActivity;
import com.doform.android.xianggucheng.IApplication;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseActivity;
import com.doform.android.xianggucheng.bean.OrderBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqDeleteOrder;
import com.doform.android.xianggucheng.bean.request_bean.ReqListOrder;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateOrder;
import com.doform.android.xianggucheng.help.AppHelp;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;


/**
 * Created by Administrator on 2017/5/10.
 */

public class OrderQueryActivity extends BaseTimePickerActivity implements OnRefreshListener, OnLoadmoreListener {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.btn_cgx)
    Button cgx;

    @BindView(R.id.btn_djs)
    Button djs;

    @BindView(R.id.btn_dfh)
    Button dfh;

    @BindView(R.id.btn_yfh)
    Button yfh;

    @BindView(R.id.btn_yzf)
    Button yzf;

    @BindView(R.id.ll)
    LinearLayout mLl;

    @BindView(R.id.tv_query_start)
    TextView mQueryStart;

    @BindView(R.id.tv_query_stop)
    TextView mQueryStop;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    private String sdate;
    private String edate;

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;

    private static final int ORDER_STATE_CGX = 1;//草稿箱
    private static final int ORDER_STATE_DJS = 3;//待接收
    private static final int ORDER_STATE_DFH = 4;//待发货
    private static final int ORDER_STATE_YFH = 5;//已发货
    private static final int ORDER_STATE_YZF = 6;//已作废

    private int ORDER_STATE = ORDER_STATE_CGX;

    private List<Button> buttons;

    private CommonAdapter<OrderBean.ListBean> mCommonAdapter;
    private List<OrderBean.ListBean> mDatas = new ArrayList<>();

    @Override
    protected int layoutResId() {
        return R.layout.activity_order_query;
    }

    @Override
    protected void init() {
        initActivity();

        String id = getIntent().getStringExtra(Constans.EXTRA_ORDER_QUERY);

        buttons = new ArrayList<>();
        buttons.add(cgx);
        buttons.add(djs);
        buttons.add(dfh);
        buttons.add(yfh);
        buttons.add(yzf);

        for (int i = 0; i < buttons.size(); i++) {
            if (id != null) {
                if (Integer.valueOf(id) == 1) {//草稿箱
                    ORDER_STATE = 1;
                    buttons.get(0).setSelected(true);
                } else if (Integer.valueOf(id) == 4) {
                    ORDER_STATE = 4;
                    buttons.get(2).setSelected(true);
                } else {

                }
            } else {
                buttons.get(0).setSelected(true);
            }
        }
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    }


    @Override
    protected void updateData() {
        super.updateData();
        refresh();
    }

    private void refresh() {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataFromService(mCurrentPage, ORDER_STATE);
    }

    private void getDataFromService(int pageId, int state) {
        HttpManager.instance()
                .getOrder( new ReqListOrder(String.valueOf(pageId), String.valueOf(state)))
                .compose(new DialogTransformer<OrderBean>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<OrderBean>() {
                    @Override
                    public void onNext(@NonNull OrderBean orderBean) {
                        notifyData(orderBean.getList());
                    }
                });
    }

    private void getDataFromService2(int pageId, int state) {
        HttpManager.instance()
                .getOrder( new ReqListOrder(String.valueOf(pageId), String.valueOf(state)))
                .subscribe(new ErrorHandleSubscriber<OrderBean>() {
                    @Override
                    public void onNext(@NonNull OrderBean orderBean) {
                        notifyData(orderBean.getList());
                    }
                });
    }


    private void notifyData(List<OrderBean.ListBean> data) {
        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (data.size() == 0 || data == null) {
            mCurrentPage--;
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadmore();
        }
        mDatas.addAll(data);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataFromService2(mCurrentPage, ORDER_STATE);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrentPage++;
        getDataFromService2(mCurrentPage, ORDER_STATE);
    }

    @Override
    protected void initListener() {

        titleBar.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLl.getVisibility() == View.VISIBLE) {
                    mLl.setVisibility(View.GONE);
                } else {
                    mLl.setVisibility(View.VISIBLE);
                }
            }
        });

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setEnableHeaderTranslationContent(false);

        mCommonAdapter = new CommonAdapter<OrderBean.ListBean>(this, R.layout.activity_order_query_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final OrderBean.ListBean bean, final int position) {
                RelativeLayout rlTitle = holder.getView(R.id.rl);
                TextView tvDate = holder.getView(R.id.tv_date);
                TextView tvOrderNum = holder.getView(R.id.tv_order_num);

                final TextView tvState = holder.getView(R.id.tv_state);
                TextView tvPrice = holder.getView(R.id.tv_price);
                TextView tvName = holder.getView(R.id.tv_name);
                TextView tvAddress = holder.getView(R.id.tv_address);
                TextView tvOrderDate = holder.getView(R.id.tv_order_date);

                Button btn_delete = holder.getView(R.id.btn_delete);

                final Button btnSend = holder.getView(R.id.btn_send);


                String mdate = bean.getAdd_date().substring(0,10);

                try {
                    if (position == 0) {//当为第一条时显示title（时间）
                        rlTitle.setVisibility(View.VISIBLE);
                        tvDate.setVisibility(View.VISIBLE);
                        tvDate.setText(mdate);
                    } else if (!mDatas.get(position - 1).getSend_date().equals(bean.getSend_date())) {//当上一条与当前时间不相等时，显示title
                        rlTitle.setVisibility(View.VISIBLE);
                        tvDate.setVisibility(View.VISIBLE);
                        tvDate.setText(mdate);
                    } else {//其余时间不显示
                        rlTitle.setVisibility(View.GONE);
                        tvDate.setVisibility(View.GONE);
                    }

                    tvOrderNum.setText(bean.getId());//订单号
                    tvPrice.setText(bean.getTotal());
                    tvName.setText(bean.getBizlnkname());
                    tvAddress.setText(bean.getBizaddr());
                    tvOrderDate.setText(bean.getAdd_date());

                    switch (Integer.parseInt(bean.getState())) {
                        case ORDER_STATE_CGX://草稿箱
                            tvState.setText("草稿箱");
                            btnSend.setVisibility(View.GONE);
                            btn_delete.setVisibility(View.VISIBLE);
                            break;
                        case ORDER_STATE_DJS://待接收
                            tvState.setText("等待接收");
                            tvState.setTextColor(getResources().getColor(R.color.order_light_red));
                            btnSend.setBackgroundColor(getResources().getColor(R.color.order_cyan));
                            btnSend.setText("接收");
                            btnSend.setVisibility(View.VISIBLE);
                            btn_delete.setVisibility(View.GONE);
                            break;
                        case ORDER_STATE_DFH://代发货
                            tvState.setText("等待发货");
                            tvState.setTextColor(getResources().getColor(R.color.order_yellow));
                            btnSend.setBackgroundColor(getResources().getColor(R.color.red));
                            btnSend.setText("发货");
                            btnSend.setVisibility(View.VISIBLE);
                            btn_delete.setVisibility(View.GONE);
                            break;
                        case ORDER_STATE_YFH://已发货
                            tvState.setText("已发货");
                            tvState.setTextColor(getResources().getColor(R.color.order_green));
                            btnSend.setBackgroundColor(Color.DKGRAY);
                            btnSend.setText("作废");
                            btnSend.setVisibility(View.VISIBLE);
                            btn_delete.setVisibility(View.GONE);
                            break;
                        case ORDER_STATE_YZF://已作废
                            tvState.setText("已作废");
                            tvState.setTextColor(Color.BLACK);
                            btnSend.setVisibility(View.GONE);
                            btn_delete.setVisibility(View.GONE);
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                }
                btn_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(bean);
                    }
                });

                //订单状态修改操作
                btnSend.setOnClickListener(new View.OnClickListener() {
                                               @Override
                                               public void onClick(View v) {
                                                   String content = btnSend.getText().toString().trim();
                                                   if ("接收".equals(content)) {
                                                       showReceiveDialog(bean, "4", position);
                                                   } else if ("发货".equals(content)) {//发货
                                                       updateState(bean, "5", position);
                                                   } else if ("作废".equals(content)) {//作废
                                                       final EditText et = new EditText(OrderQueryActivity.this);
                                                       et.setTransformationMethod(PasswordTransformationMethod.getInstance());
                                                       et.setHint("请输入密码");
                                                       et.setGravity(Gravity.CENTER);
                                                       new AlertDialog.Builder(OrderQueryActivity.this)
                                                               .setView(et)
                                                               .setTitle("身份验证")
                                                               .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                                                           @Override
                                                                           public void onClick(DialogInterface dialog, int which) {
                                                                               String trim = et.getText().toString().trim();
                                                                               if (AppHelp.getInstance().getPassword().equals(trim)) {
                                                                                   updateState(bean, "6", position);
                                                                               } else {
                                                                                   TsUtils.showToast("密码不正确");
                                                                               }
                                                                               dialog.dismiss();
                                                                           }
                                                                       }
                                                               )
                                                               .create()
                                                               .show();
                                                   }
                                               }
                                           }
                );
            }

        };


        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(OrderQueryActivity.this, OrderDetailActivity.class);
                intent.putExtra(Constans.ORDER_DETAIL_ID, mDatas.get(position).getId());
                intent.putExtra(Constans.ORDER_DETAIL_GUID, mDatas.get(position).getGuid());
                startActivityForResult(intent, Constans.REQUEST_ORDER_DETAILE);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mRecyclerView.setAdapter(mCommonAdapter);

    }

    private void showDialog(final OrderBean.ListBean bean) {

        new AlertDialog.Builder(this)
                .setMessage("该数据删除后将无法恢复，请确认是否要删除?")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteItem(bean);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                .show();
    }

    /**
     * 草稿箱 删除订单
     *
     * @param bean
     */
    private void deleteItem(OrderBean.ListBean bean) {
        HttpManager
                .instance()
                .deleteOrder(new ReqDeleteOrder(bean.getId(), bean.getGuid()))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer integer) {
                        refresh();
                    }
                });
    }

    private void showReceiveDialog(final OrderBean.ListBean bean, final String state, final int position) {
        if (Double.valueOf(bean.getHaspay()) < 1) {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("该订单未付款！确认接收？")
                    .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            updateState(bean, state, position);
                        }
                    }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create()
                    .show();
        } else {
            updateState(bean, state, position);
        }

    }

    /**
     * 接收订单
     *
     * @param bean
     * @param position
     */
    private void updateState(final OrderBean.ListBean bean, String state, final int position) {

        HttpManager
                .instance()
                .updateOrder(new ReqUpdateOrder(bean.getId(), bean.getGuid(), state,
                        bean.getWhid(), bean.getWhname(), bean.getLibid(), bean.getLibname(), bean.getPaytype(), bean.getHaspay()))
                .compose(new DialogTransformer<Integer>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer integer) {
                        mDatas.remove(position);
                        mCommonAdapter.notifyDataSetChanged();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Constans.REQUEST_ORDER_DETAILE:
                if (data != null) {
                    String id = data.getStringExtra(Constans.EXTRA_ORDER_QUERY_DETAIL);
                    for (int i = 0; i < buttons.size(); i++) {
                        if (id != null) {
                            if (Integer.valueOf(id) == 4) {
                                ORDER_STATE = 4;
                                buttons.get(2).setSelected(true);
                                buttons.get(0).setSelected(false);
                                buttons.get(1).setSelected(false);
                            } else if (Integer.valueOf(id) == 5) {
                                ORDER_STATE = 5;
                                buttons.get(3).setSelected(true);
                                buttons.get(2).setSelected(false);
                            } else if (Integer.valueOf(id) == 6) {
                                ORDER_STATE = 6;
                                buttons.get(4).setSelected(true);
                                buttons.get(3).setSelected(false);
                            } else {
                            }
                        }
                    }
                    refresh();
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }



    @Override
    protected void showView() {
        titleBar.setTextTitle("订单查询");
        titleBar.setRightText("查询");
        titleBar.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }


    @OnClick({R.id.btn_cgx, R.id.btn_djs, R.id.btn_dfh, R.id.btn_yfh, R.id.btn_yzf,
            R.id.btn_query, R.id.tv_query_start, R.id.tv_query_stop})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_cgx:
                cgx.setSelected(true);
                djs.setSelected(false);
                dfh.setSelected(false);
                yfh.setSelected(false);
                yzf.setSelected(false);
                ORDER_STATE = ORDER_STATE_CGX;
                break;
            case R.id.btn_djs:
                cgx.setSelected(false);
                djs.setSelected(true);
                dfh.setSelected(false);
                yfh.setSelected(false);
                yzf.setSelected(false);
                ORDER_STATE = ORDER_STATE_DJS;
                break;
            case R.id.btn_dfh:
                cgx.setSelected(false);
                djs.setSelected(false);
                dfh.setSelected(true);
                yfh.setSelected(false);
                yzf.setSelected(false);
                ORDER_STATE = ORDER_STATE_DFH;
                break;
            case R.id.btn_yfh:
                cgx.setSelected(false);
                djs.setSelected(false);
                dfh.setSelected(false);
                yfh.setSelected(true);
                yzf.setSelected(false);
                ORDER_STATE = ORDER_STATE_YFH;
                break;
            case R.id.btn_yzf:
                cgx.setSelected(false);
                djs.setSelected(false);
                dfh.setSelected(false);
                yfh.setSelected(false);
                yzf.setSelected(true);
                ORDER_STATE = ORDER_STATE_YZF;
                break;
            case R.id.btn_query:
                befroeQuery();
                break;
            case R.id.tv_query_start:
                pvTime.show(mQueryStart);
                break;
            case R.id.tv_query_stop:
                pvTime2.show(mQueryStop);
                break;
            default:
                break;
        }
        refresh();
    }

    private void befroeQuery() {
            String sdate = mQueryStart.getText().toString().trim();
            String edate = mQueryStop.getText().toString().trim();

//            getDataFromService(sdate, edate);
    }

    private void initActivity() {
        List<BaseActivity> activities = IApplication.getInstance().getActivities();
        for (int i = 0; i < activities.size(); i++) {
            BaseActivity activity = activities.get(i);
            if ("activity.MainActivity".equals(activity.getLocalClassName())) {
            } else if ("activity.downorder.OrderQueryActivity".equals(activity.getLocalClassName())) {
            } else {
                activity.finish();
            }
        }
    }
}
